import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:search_people/page/dynamic/subs/dynamic_leaders/cell.dart';
import 'package:search_people/utils/component/list/section.dart';
import 'package:search_people/utils/key_val_model.dart';
import 'package:search_people/utils/storage.dart';
import 'package:search_people/utils/util.dart';
import 'package:search_people/value/topcolors.dart';

import '../../../../bean/search/hot_people.dart';
import 'index.dart';
import 'widgets/widgets.dart';

class DynamicSearchController extends GetxController {
  DynamicSearchController();

  final state = DynamicSearchState();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  void actionHistoryTap(String t) {
    state.tc?.text = t;
    state.searchInputText = t;
    setupResults();
  }

  void onInputChanged() {
    var lastSearchState = state.isSearching;
    state.searchInputText = state.tc?.text;
    if (state.isSearching != lastSearchState) {
      initData();
    }
    if (state.isSearching) {
      setupResults();
    }
  }

  void onSubmmit(String t) {
    state.tc?.text = t;
    List data = SpUtil().getJSON(StorageKeys.dynamic_history) ?? [];
    var _t = t.removeAllWhitespace;
    if (_t.isEmpty) {
      return;
    }
    data.add(_t);
    SpUtil().setJSON(StorageKeys.dynamic_history, data);
    state.his = data.map((e) => KeyValModel(key: e)).toList();
    setupResults();
  }

  void initData() async {
    List? data = SpUtil().getJSON(StorageKeys.dynamic_history);
    state.his = data?.map((e) => KeyValModel(key: e.toString())).toList();
    List<KeyValModel> hots = await getHotData();
    state.initList = [
      SectionModel(
          index: 0,
          sectionHeader: const HotSearchTitleWidget(),
          itemBuilder: (ctx, idx) {
            return InkWell(
              child: HotSearchCell(md: hots[idx]),
              onTap: () {
                Get.toNamed(RouterPath.dynamic_person);
              },
            );
          },
          items: hots)
    ];

    update();
  }

  void setupResults() {
    state.results = [
      SectionModel(
          index: 0,
          sectionHeader: Container(
            height: 40.r,
            alignment: Alignment.centerLeft,
            child: Text(
              '观政极速搜为您找到2位领导和321条动态',
              style: TextStyle(
                color: TopColors.black_33,
                fontSize: 12.sp,
              ),
            ),
          ),
          itemBuilder: (ctx, idx) {
            return InkWell(
              child: PersonCell(
                idx: idx,
              ),
              onTap: () {
                Get.toNamed(RouterPath.dynamic_person);
              },
            );
          },
          items: [1, 2]),
      SectionModel(
        index: 0,
        itemBuilder: (ctx, idx) {
          return DynamicLeaderCell();
        },
        items: List.generate(10, (index) => index),
      ),
    ];
    update();
  }

  //获取热搜人物
  Future<List<KeyValModel>> getHotData() async {
    var resultData = await Api.hot_people();
    List data = resultData.data;
    var hots = data.map((e) => HotPeople.fromJson(e)).toList();

    return hots
        .asMap()
        .map(
          (key, e) => MapEntry(
            key,
            KeyValModel(
              key: e.leaderName ?? '',
              idx: key,
              val: e.leaderId,
              detail: e.currentPosition,
            ),
          ),
        )
        .values
        .toList();
  }

  void actionDeleteAllHistory() {
    SpUtil().remove(StorageKeys.dynamic_history);
    state.his = null;
    update();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    initData();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.tc?.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
